# -*-coding:utf-8 -*-
import requests
from lxml import etree
import pymysql
'虎牙视频各分区热度和（功能19）'

# 地址数组
urlArr = [
    "https://v.huya.com/rank/30ssv.html",
    "https://v.huya.com/rank/vhuyajdqs.html",
    "https://v.huya.com/rank/cjzc.html",
    "https://v.huya.com/rank/vhuyawzry.html",
    "https://v.huya.com/rank/vhuyalol.html",
    "https://v.huya.com/rank/id5.html",
    "https://v.huya.com/rank/vhuyamc.html",
    "https://v.huya.com/rank/blzy.html",
    "https://v.huya.com/rank/consolegame.html"
]
# 分区名数组
areaNameArr = ["短视频", "绝地求生", "和平精英", "王者荣耀", "英雄联盟", "第五人格", "我的世界", "堡垒之夜", "主机游戏"]


# 获取页面数据
def getPageInfo():
    # 返回一个分区排行榜评分的数组
    scoreArr = []
    for url in urlArr:
        response = requests.get(url=url)
        response.encoding = 'utf-8'
        tree = etree.HTML(response.text)
        list = tree.xpath("//div[@class='vhuya-rank-cont']/ul/li")
        # 分区视频总评分
        sumScore = 0
        for li in list:
            # 视频得分
            score = li.xpath("./div[2]/text()")[0].strip()
            sumScore = sumScore + int(score)
        scoreArr.append(sumScore)
    return scoreArr


# 创建MySQL连接函数（当做固定）
def getMysqlConn():
    conn = pymysql.connect(host='106.13.194.7',
                           port=3306,
                           user='rdsroot',
                           password='abc123456',
                           db='huya',
                           charset='utf8')
    # 创建操作的游标
    cursor = conn.cursor()
    # 设置字符编码及自动提交
    cursor.execute('set names utf8')  # 固定格式
    cursor.execute('set autocommit=1')
    # 设置自动提交
    return conn, cursor


# 保存数据
def saveVideoData(scoreArr):
    conn, cursor = getMysqlConn()
    # sql语句
    sql = "insert into t_videoArea (id,area,score) values(REPLACE(UUID(),'-',''),%s,%s)"
    index = 0
    for score in scoreArr:
        add_data = (areaNameArr[index], score)
        # 这里会把sql语句中的%s替换掉
        cursor.execute(sql, add_data)
        index = index + 1
    print("分区评分插入数据完成")
    # 关闭连接
    cursor.close()
    conn.close()


if __name__ == '__main__':
    scoreArr = getPageInfo()
    saveVideoData(scoreArr)
